home *** CD-ROM | disk | FTP | other *** search
- Path: tank.news.pipex.net!pipex!iol!usenet
- From: jab@iol.ie (J Alan Brogan)
- Newsgroups: comp.lang.c
- Subject: Re: I need help on putting 2 strings together into 1(concatenate)
- Date: Wed, 21 Feb 1996 15:17:59 GMT
- Organization: Ireland On-Line
- Message-ID: <4gfd3g$6oa@barnacle.iol.ie>
- References: <4gcr1b$ft3@cloner4.netcom.com>
- Reply-To: jab@iol.ie
- NNTP-Posting-Host: dialup-029.tralee.iol.ie
- X-Newsreader: Forte Free Agent 1.0.82
-
- spdcool@ix.netcom.com(SPD) wrote:
-
- <SNIP>
- >struct data {
- > char *full_name;
- > int age;
- > float salary;
- > };
-
- >struct name {
- > char *first1, *last1;
- > };
-
-
- >int main(void)
- >{
- > struct name fname[3], lname[3];
- > struct data secret[5];
- > int i, ran;
-
- > fname[o].first1 = "Joe";
- > fname[1].first1 = "Michael";
- > fname[2].first1 = "Bruce";
- > lname[0].last1 = "Jordan";
- > lname[1].last1 = "Willis";
- > lname[2].last1 = "Jackson";
-
-
- > randomize()
- > for (i = 0; i < 5; ++i) {
- > e = random(3);
- > secret[i].full_name = fname[e].first1;/* the trouble some part begin
- > e = random(3);
- > strcat(secret[i].full_name," ");
- > strcat(secret[i].full_name,lname[e].last1); /*trouble ends here*/
-
- <SNIP>
-
- You haven't allocated any storage for secret[i].full_name. And
- secret[i].full_name = fname[e].first1;
- makes it point at, eg "Joe", ie you are not copying "Joe" to your
- record, you are only making your record point to where "Joe" is alreay
- stored in memory.
-
- The next two lines try to concatenate more characters on to
- secret[i].full_name, ie they try to copy chars into memory straight
- after where, eg "Joe" is stored. So what happens next is undefined, ie
- anything is possible.
-
- So your program might start overwriting the other names, or it might
- crash, or it might start printing the FAQ at you (if you're really
- lucky).
-
- Try setting aside some memory that _you_ have control over (as opposed
- to memory the compiler sets aside for, eg, "Joe"), and if you want to
- assign a string, use strcpy(), not =.
-
- For example :
-
- # define YOUR_SIZE 30
- struct data {
- char full_name[YOUR_SIZE];
- int age;
- float salary;
- };
-
- for (i = 0; i < 5; ++i) {
- e = random(3);
- strcpy(secret[i].full_name,fname[e].first1);
- /* etc */
- }
-
-
- Bye from
- Alan @ Kerry, Ireland
-
-